package com.bana.fvs.app.module.detaile;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import com.bana.fvs.R;
import com.bana.fvs.app.base.BaseActivity;
import com.bana.fvs.app.common.ConstantsField;
import com.bana.fvs.app.main.adapter.FogControllerAdapter;
import com.bana.fvs.app.main.entity.FogControllerItem;
import com.bana.fvs.app.main.entity.FogZoneListItemBean;
import com.bana.fvs.app.module.detaile.entity.AreaControllerDetailBean;
import com.bana.fvs.app.module.detaile.entity.CommonEntity;
import com.bana.fvs.app.module.detaile.entity.FogAreaInfoBean;
import com.bana.fvs.app.module.detaile.entity.FoglightDetailInfo;
import com.bana.fvs.app.module.detaile.entity.UpdateWorkModeResultBean;
import com.bana.fvs.app.module.detaile.entity.VisibilityControllerDetailBean;
import com.bana.fvs.app.module.tab2.tab2Detail.entity.EquipListItemBean;
import com.bana.fvs.app.mvp.contract.DetailContract;
import com.bana.fvs.app.mvp.presenter.DetailPresenter;
import com.bana.fvs.app.other.xrecyclerview.XRecyclerView;
import com.bana.fvs.app.util.CommonUtils;
import com.bana.fvs.app.util.TimeUtils;
import com.bana.fvs.app.util.UserInfoUtils;
import com.bana.fvs.app.view.TextImageLayout;
import com.google.gson.Gson;
import com.wei.commonlibrary.manager.RxBus;
import com.wei.commonlibrary.net.CommException;
import com.wei.commonlibrary.titlebar.BaseTitleBarView;
import com.wei.commonlibrary.utils.GlobalContext;
import com.wei.commonlibrary.utils.LogUtil;
import com.wei.commonlibrary.utils.ToastUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.functions.Action1;

/**
 * Created by wei on 2018/2/12.
 * 详情页
 */

/**
 * Author : yanftch
 * Date   : 2018/3/16
 * Time   : 22:39
 * Desc   : 0.能见度检测仪    1.区域控制器      2.雾灯     3.雾区详情   4.气象仪
 */

public class EquipmentDetailActivity extends BaseActivity<DetailPresenter> implements DetailContract.AbsDetailView {
    private static final String TAG = "dah_EquipmentDetail";

    public static final String UPDATE_JCY = "jcy";
    private static final String UPDATE_WD = "wd";

    @BindView(R.id.detail_toolbar)
    BaseTitleBarView baseTitleBarView;
    @BindView(R.id.fl_detail_info)
    FrameLayout fl_detail_info;
    //    @BindView(R.id.eqiup_name)
//    TextView tv_eqiup_name;
    @BindView(R.id.ivTopRefresh)
    ImageView mIvTopRefresh;

    /**
     * 雾区详情
     */
    private TextView tvName;//雾区名称
    private TextImageLayout tvKzcl;//控制策略
    private TextImageLayout tvNjdLevel;//能见度等级
    private TextImageLayout tvNjd;//能见度等级
    private TextImageLayout tvOneMinuteNjd;//一分钟能见度
    private TextImageLayout tvTenMinuteNjd;//十分钟能见度
    private TextImageLayout tvWeather;//天气
    private TextImageLayout tl_work_mode;//工作模式
    private Spinner sp_work_mode;
    private TextImageLayout tl_foglight_controller;//雾灯控制
    private TextImageLayout refreshTime;//更新时间
    private Switch timeSwitch;
    private TextView tvSdgy;
    private TextView tvQxgy;
    private TextImageLayout tvCountdown;//倒计时

    private RecyclerView fogControllerListView;
    private List<FogControllerItem> datas;
   private FogControllerAdapter fogControllerAdapter;
    private TextImageLayout tvLd;//天气
    private TextImageLayout tvPl;//天气
    private TextImageLayout tvZkb;//天气
    private TextImageLayout tvDzs;//天气


    /**
     * 雾灯详情
     */
    private TextImageLayout item_equipmentnumber;//设备编码
    private TextImageLayout item_control;//所属控制器
    private TextImageLayout item_voltage;//蓄电池电压
    private TextImageLayout item_deviceStatus;//设备状态
    private TextImageLayout item_lampTemp;//雾灯温度
    private TextImageLayout itemDoorStatus;//门状态
    private TextImageLayout itemTemperature;//温度状态
    private TextImageLayout itemVoltageStatus;//电压状态
    private TextImageLayout itemLEDStatus;//LED状态
    private TextImageLayout itemRadarStatus;//雷达状态
    private TextImageLayout itemDevicePairing;//设备配对
    private TextImageLayout itemFaultDescription;//故障描述
    private TextImageLayout itemRefreshTime;//刷新时间
    private TextImageLayout tl_solar_energy;//太阳能电压


    /**
     * 区域控制器&&能见度检测仪
     */
    private TextImageLayout itemsEquipCode;//设备编码
    private TextImageLayout itemsBelongFogZone;//所属雾区
    private TextImageLayout itemsEquipStqtus;//设备状态
    private TextImageLayout itemsProplemDesc;//故障描述
    private TextImageLayout itemsRefreshTime;//刷新时间

    //区域控制器
    private TextImageLayout tl_device_name;
    private TextImageLayout tl_control_code;
    private TextImageLayout tl_fog_area_alarm;
    private TextImageLayout tl_use_radar;
    private TextImageLayout tl_inspec_interval;
    private TextImageLayout tl_radar_status;
    private TextImageLayout tl_device_matching;
    private TextImageLayout tl_fog_lamp_list;
    private TextImageLayout tl_code;


    //能见度检测仪
    private TextImageLayout tl_comm_params;
    private TextImageLayout tl_alarm_offline;
    private TextImageLayout tl_alarm_online;
    private TextImageLayout tl_alarm_line;//报警阈值

    public static final String EXTRA_PAGETYPE = "extra_pageType";
    public static final String EXTRA_CODE = "extra_code";
    public static final String EXTRA_KZQBM = "extra_kzqbm";
    public static final String EXTRA_BEAN = "extra_bean";
    private int pageType;
    private String typeCode, kzqbm;//编码？是的
    private String workModel;
    private String lightModel;

    private boolean isError = false;

    private FogZoneListItemBean fogZone;
    private EquipListItemBean equipListItemBean;
    private FoglightDetailInfo foglightDetailInfo;

    /**
     * @param context
     * @param pageType 2.雾灯 3.雾区详情 1.区域控制器  0.能见度检测仪
     * @param code     详情页编码[雾区编码、设备编码...],不同的接口，需要用到这个参数
     */
    public static void startAction(Context context, int pageType, String code, String kzqbm) {
        Intent intent = new Intent(context, EquipmentDetailActivity.class);
        intent.putExtra(EXTRA_PAGETYPE, pageType);
        intent.putExtra(EXTRA_CODE, code);
        if (!TextUtils.isEmpty(kzqbm)) {
            intent.putExtra(EXTRA_KZQBM, kzqbm);
        }
        context.startActivity(intent);
    }

    public static void startAction(Context context, int pageType, Serializable bean) {
        Intent intent = new Intent(context, EquipmentDetailActivity.class);
        intent.putExtra(EXTRA_PAGETYPE, pageType);
        intent.putExtra(EXTRA_BEAN, bean);

        context.startActivity(intent);
    }


    private void http_getData() {
        if (pageType == 3) {
            //雾区详情的接口
            // mPresenter.http_fogAreaEquipment(this, UserInfoUtils.getInstance().getToken(mContext), typeCode);

            fogZone = (FogZoneListItemBean) getIntent().getSerializableExtra(EXTRA_BEAN);
            fogAreaInfo(fogZone);
        } else if (pageType == 2) {
            //雾灯详情的接口
            //mPresenter.http_foglightEquipment(this, UserInfoUtils.getInstance().getToken(mContext), typeCode, kzqbm);

            foglightDetailInfo = (FoglightDetailInfo) getIntent().getSerializableExtra(EXTRA_BEAN);
            foglightInfo(foglightDetailInfo);

        } else if (pageType == 1) {
            //区域控制器
            //mPresenter.http_controllerEquipment(this, UserInfoUtils.getInstance().getToken(mContext), typeCode);
            equipListItemBean = (EquipListItemBean) getIntent().getSerializableExtra(EXTRA_BEAN);
            onResponse(equipListItemBean);
        } else if (pageType == 0) {
            //能见度检测仪
            equipListItemBean = (EquipListItemBean) getIntent().getSerializableExtra(EXTRA_BEAN);
            visibilityDetectInfo(equipListItemBean);
            //  mPresenter.http_visibilityDetectionEquipment(this, UserInfoUtils.getInstance().getToken(mContext), typeCode);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //能见度检测仪

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (pageType == 3) {
            Observable<Object> register = RxBus.getInstance().register(UPDATE_JCY);
            RxBus.getInstance().onEvent(register, obj -> {
                if (obj == null) return;
                setPushVisisblityInfo((String) obj);
                //LogUtil.e("RxBus",obj.toString());
            });
        }

    }

    @Override
    public int setLayout() {
        return R.layout.activity_eqiupment_detail;
    }

    @Override
    public void setTitle() {
        mBaseTitleBarView.setVisibility(View.GONE);
        baseTitleBarView.setTitleText(getString(R.string.equipment_detail));
        baseTitleBarView.setLeftDrawable(-1);
        baseTitleBarView.setLeftTitleGone();

        baseTitleBarView.addOnLeftTitleClickListener(v -> finish());
    }


    int countSecond = 0;


    @Override
    public void initWidget() {
        parserIntent();
        View view = null;
        switch (pageType) {
            case 2://雾灯详情
                baseTitleBarView.setTitleText(getString(R.string.fogLight_detail));
                view = View.inflate(this, R.layout.layout_foglight_detail, null);
                /**------*/
                item_equipmentnumber = view.findViewById(R.id.item_equipmentnumber);
                item_control = view.findViewById(R.id.item_control);
                item_voltage = view.findViewById(R.id.item_voltage);
                item_deviceStatus = view.findViewById(R.id.item_deviceStatus);
                item_lampTemp = view.findViewById(R.id.item_lampTemp);
                tl_solar_energy = view.findViewById(R.id.tl_solar_energy);
                itemDoorStatus = view.findViewById(R.id.itemDoorStatus);
                itemTemperature = view.findViewById(R.id.itemTemperature);
                itemVoltageStatus = view.findViewById(R.id.itemVoltageStatus);
                itemLEDStatus = view.findViewById(R.id.itemLEDStatus);
                itemRadarStatus = view.findViewById(R.id.itemRadarStatus);
                itemDevicePairing = view.findViewById(R.id.itemDevicePairing);
                itemFaultDescription = view.findViewById(R.id.itemFaultDescription);
                itemRefreshTime = view.findViewById(R.id.itemRefreshTime);
                /**------*/
                break;
            case 3://雾区详情
                baseTitleBarView.setTitleText(getString(R.string.fogArea_detail));
                view = View.inflate(this, R.layout.layout_fogarea_detail, null);
                initFogAreaDetailInfo(view);
                /**------*/
                tvName = view.findViewById(R.id.tvName);
                tvKzcl = view.findViewById(R.id.tl_kzcl);
                tvNjdLevel = view.findViewById(R.id.tvNjdLevel);
                tvNjd = view.findViewById(R.id.tvNjd);
                tvOneMinuteNjd = view.findViewById(R.id.tvOneMinuteNjd);
                tvTenMinuteNjd = view.findViewById(R.id.tvTenMinuteNjd);
                tvTenMinuteNjd = view.findViewById(R.id.tvTenMinuteNjd);
                tvWeather = view.findViewById(R.id.tvWeather);
                tl_work_mode = view.findViewById(R.id.tl_work_mode);
                // sp_work_mode = view.findViewById(R.id.sp_work_mode);
                tl_foglight_controller = view.findViewById(R.id.tl_foglight_controller);

                fogControllerListView = view.findViewById(R.id.fogControllerListView);
                datas=new ArrayList<>();
                fogControllerAdapter=new FogControllerAdapter(datas);
                fogControllerListView.setLayoutManager(new LinearLayoutManager(this));
                fogControllerListView.setAdapter(fogControllerAdapter);


                refreshTime = view.findViewById(R.id.refreshTime);
                tvCountdown = view.findViewById(R.id.countdown);
                timeSwitch = view.findViewById(R.id.switch1);
//                tvLd=view.findViewById(R.id.tl_foglight_ld);
//                tvPl=view.findViewById(R.id.tl_foglight_pl);
//                tvZkb=view.findViewById(R.id.tl_foglight_zkb);
//                tvDzs=view.findViewById(R.id.tl_foglight_dzs);

                tvSdgy = view.findViewById(R.id.tv_sdgy);
                tvSdgy.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        FogLightControllerActivity.startActionForResult(mActivity, lightModel, typeCode, fogZone);
                    }
                });

                tvQxgy = view.findViewById(R.id.tv_qxgy);

                tvQxgy.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (fogZone == null)
                            return;

                        if (fogZone.getGzms() == 1) {
                            ToastUtil.showShort(mContext, "未手动干预");
                            return;
                        }


                        HashMap<String, Object> data = new HashMap<>();

                        //                                "wqbm": "30",
                        //"gzms": "2",
                        //"wdkz": 1,
                        //                 "ldsc": "250",
//                                "mdsc": "750",
//                                "hdys": "3",
//                                "mqys": "3",
//                                "hsjsdzsl": "3",

//                                "sfds": 0,
//                                "wdld": "5",
//                                "kzcl": 1,
//                                "zkb": 1
//                                "sspl": 1,


//                                "sdsc": "5",
//                                "wdlddj": "1",


                        data.put("wqbm", fogZone.getWqbm());
                        data.put("gzms", "1");
                        data.put("wdkz", fogZone.getWdkz());
                        data.put("ldsc", fogZone.getLdsc() + "");
                        data.put("mdsc", fogZone.getMdsc() + "");
                        data.put("hdys", fogZone.getHdys() + "");
                        data.put("mqys", fogZone.getMqys() + "");
                        data.put("hsjsdzsl", fogZone.getHsjsdzsl() + "");
                        // data.put("wdlddj", fogZone.getWdlddj()+"");
                        if (fogZone.isSfds())
                            data.put("sfds", 1);
                        else
                            data.put("sfds", 0);
                        data.put("wdld", fogZone.getWdld());
                        data.put("kzcl", fogZone.getKzcl());
                        data.put("sspl", fogZone.getSspl());
                        data.put("zkb", fogZone.getZkb());

                        data.put("cxsj", fogZone.getCxsj());
                        data.put("wdlddj", fogZone.getWdlddj());


                        mPresenter.http_foglightWorkModeUpdate(mActivity, UserInfoUtils.getInstance().getToken(mContext), data);
                    }
                });


                /**------*/
                break;
            //能见度检测仪
            case 0: {
                baseTitleBarView.setTitleText(getString(R.string.visibility_detail));
                view = View.inflate(this, R.layout.layout_visibility_detail, null);
                initFogAreaDetailInfo(view);
                itemsEquipCode = view.findViewById(R.id.itemsEquipCode);
                itemsBelongFogZone = view.findViewById(R.id.itemsBelongFogZone);
                tl_device_name = view.findViewById(R.id.tl_device_name);
                tl_comm_params = view.findViewById(R.id.tl_comm_params);
                tl_work_mode = view.findViewById(R.id.tl_work_mode);
                tl_alarm_offline = view.findViewById(R.id.tl_alarm_offline);
                tl_alarm_line = view.findViewById(R.id.tl_alarm_line);
                tl_alarm_online = view.findViewById(R.id.tl_alarm_online);
                itemsEquipStqtus = view.findViewById(R.id.itemsEquipStqtus);
                itemsRefreshTime = view.findViewById(R.id.itemsRefreshTime);
            }
            break;
            case 1: {//区域控制器
                baseTitleBarView.setTitleText(getString(R.string.controller_detail));
                view = View.inflate(this, R.layout.layout_controller_detail, null);
                itemsEquipCode = view.findViewById(R.id.itemsEquipCode);
                tl_device_name = view.findViewById(R.id.tl_device_name);
                tl_code = view.findViewById(R.id.tl_code);
                itemsBelongFogZone = view.findViewById(R.id.itemsBelongFogZone);
                tl_control_code = view.findViewById(R.id.tl_control_code);
                tl_fog_area_alarm = view.findViewById(R.id.tl_fog_area_alarm);
                tl_use_radar = view.findViewById(R.id.tl_use_radar);
                tl_inspec_interval = view.findViewById(R.id.tl_inspec_interval);
//                tl_radar_status = view.findViewById(R.id.tl_radar_status);
                tl_device_matching = view.findViewById(R.id.tl_device_matching);
                itemsEquipStqtus = view.findViewById(R.id.itemsEquipStqtus);
                itemsRefreshTime = view.findViewById(R.id.itemsRefreshTime);

                tl_fog_lamp_list = view.findViewById(R.id.tl_fog_lamp_list);
            }
            break;
        }
        if (view != null) {
            fl_detail_info.addView(view);
        }
        http_getData();
        mIvTopRefresh.setOnClickListener(this);
    }

    private void parserIntent() {
        Intent intent = getIntent();
        pageType = intent.getIntExtra(EXTRA_PAGETYPE, 0);
        typeCode = intent.getStringExtra(EXTRA_CODE);
        if (intent.hasExtra(EXTRA_KZQBM)) {
            kzqbm = intent.getStringExtra(EXTRA_KZQBM);
        }
        /**
         * 测试代码
         */
//        //能见度检测仪
//        pageType = 0;
//        typeCode = "1";
//        //区域控制器
//        pageType = 1;
//        typeCode = "1";
//        //雾灯详情
//        pageType = 2;
//        typeCode = "1";
    }

    /**
     * 雾区详情页事件及文案绑定
     */
    private void initFogAreaDetailInfo(View view) {
//        view.findViewById(R.id.tl_work_mode).setOnClickListener(v -> {
//            if (isError) return;
//            WorkModeControllerActivity.startAction(this, workModel, pageType == 0 ? 2 : 1);//工作模式
//        });

        View tl_foglight_controller = view.findViewById(R.id.tl_foglight_controller);
        if (tl_foglight_controller == null) return;

//        tl_foglight_controller.setOnClickListener(v -> {
//            if (isError) return;
//            // TODO: 2018/3/14 添加参数！！！！！！！
//            //String gzms = String.valueOf(sp_work_mode.getSelectedItemPosition() + 1);
//            FogLightControllerActivity.startActionForResult(this, lightModel, typeCode,  fogZone);
//        });
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.ivTopRefresh:
                http_getData();
                break;
        }
    }

    @Override
    protected void initPresenter() {
        mPresenter.setView(this);
    }

    @Override
    public void onError(CommException e) {
        isError = true;
        ToastUtil.showShort(GlobalContext.context, e.getMessage());
    }

    /**
     * 区域控制
     */
    @Override
    public void onResponse(AreaControllerDetailBean bean) {
        isError = false;
        if (bean == null) return;
        itemsEquipCode.setRightText(String.valueOf(bean.getSbbm()));//设备编码
        tl_device_name.setRightText(bean.getSbmc());//控制器名称
        itemsBelongFogZone.setRightText(bean.getWqmc());//所属雾区
        tl_control_code.setRightText(String.valueOf(bean.getKzqbsm()));//控制器标识码
        tl_fog_area_alarm.setRightText(bean.getWdbj());//雾灯报警
        tl_use_radar.setRightText(bean.getSfsyldsm());//使用雷达
        tl_inspec_interval.setRightText(String.valueOf(bean.getWdxjjg()) + "分钟");//巡检间隔
//        tl_radar_status.setRightText(bean.getLdsc());//雷达状态
        itemsEquipStqtus.setRightText(bean.getSbztsm());//设备状态
//        itemsProplemDesc.setRightText(bean.getGzms());//故障描述
        itemsRefreshTime.setRightText(bean.getGxsjsm());//更新时间
//        int lampNum = bean.getJsdz() - bean.getKsdz() + 1;
        int lampNum = bean.getWdsl();
        tl_fog_lamp_list.setRightText(String.valueOf(lampNum));//雾灯数量
        //雾区编码
        tl_code.setRightText(bean.getKsdz() + "~" + bean.getJsdz());
        tl_code.setOnClickListener(v -> {
            FogLampListActivity.startAction(this, String.valueOf(bean.getKzqbm()));
        });
    }

    public void onResponse(EquipListItemBean bean) {
        isError = false;
        if (bean == null) return;
        itemsEquipCode.setRightText(String.valueOf(bean.getKzqbm()));//设备编码
        tl_device_name.setRightText(bean.getName());//控制器名称
        itemsBelongFogZone.setRightText(bean.getWqmc());//所属雾区
        tl_control_code.setRightText(String.valueOf(bean.getKzqbsm()));//控制器标识码
        tl_fog_area_alarm.setRightText(bean.getWdbjsm());//雾灯报警
        tl_use_radar.setRightText(bean.getSfsyldsm());//使用雷达
        tl_inspec_interval.setRightText(String.valueOf(bean.getWdxjjg()) + "分钟");//巡检间隔
//        tl_radar_status.setRightText(bean.getLdsc());//雷达状态
        itemsEquipStqtus.setRightText(bean.getSbztsm());//设备状态
//        itemsProplemDesc.setRightText(bean.getGzms());//故障描述
        itemsRefreshTime.setRightText(bean.getGxsjsm());//更新时间
//        int lampNum = bean.getJsdz() - bean.getKsdz() + 1;
        int lampNum = bean.getWdsl();
        tl_fog_lamp_list.setRightText(String.valueOf(lampNum));//雾灯数量
        //雾区编码
        tl_code.setRightText(bean.getKsdz() + "~" + bean.getJsdz());
        tl_code.setOnClickListener(v -> {
            FogLampListActivity.startAction(this, String.valueOf(bean.getKzqbm()));
        });
    }


    /**
     * 雾区详情
     */

    public void fogAreaInfo(FogZoneListItemBean fogAreaInfoBean) {
        isError = false;
        if (fogAreaInfoBean == null) return;
//        tv_eqiup_name.setText(fogAreaInfoBean.getWqmc());//雾区名称
        tvName.setText(fogAreaInfoBean.getWqmc());
        tvKzcl.setRightText(fogAreaInfoBean.getKzclsm());
        if (!fogAreaInfoBean.getNjddj().equals("-1"))
            tvNjdLevel.setRightText(fogAreaInfoBean.getNjddj());//能见度等级
        else
            tvNjdLevel.setRightText("-");//能见度等级
        tvNjd.setRightText(String.format("%dm", fogAreaInfoBean.getNjd()));//能见度
        if ( fogAreaInfoBean.getNjdyfz() > ConstantsField.MAXNJD)
            tvOneMinuteNjd.setRightText(String.format("%dm", fogAreaInfoBean.getNjdyfz()));//一分钟能见度
        else
            tvOneMinuteNjd.setRightText("-");
        if (fogAreaInfoBean.getNjdyfz() > ConstantsField.MAXNJD) {
            tvTenMinuteNjd.setRightText(String.format("%dm", fogAreaInfoBean.getNjdsfz()));//十分钟能见度
//            tvWeather.setRightText("晴朗");
//            tvWeather.setRightText(fogAreaInfoBean.getLmzt());
            tvWeather.setRightText(fogAreaInfoBean.getTqdmsm());
        } else {
            tvTenMinuteNjd.setRightText("-");
//            tvWeather.setRightText("-");
//            tvWeather.setRightText(fogAreaInfoBean.getLmzt());
            tvWeather.setRightText(fogAreaInfoBean.getTqdmsm());
            //tvWeather.setRightText(detailBean.getLmzt());//天气
        }
        tl_work_mode.setRightText(fogAreaInfoBean.getGzmssm());//工作模式
        //sp_work_mode.setSelection(fogAreaInfoBean.getGzms() - 1);
//        tl_foglight_controller.setRightText(fogAreaInfoBean.getWdkzsm());//雾灯控制
//
//        tl_foglight_controller.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                FogLampStateActivity.startAction(mContext, fogZone);
//            }
//        });
        datas.clear();
        datas.addAll(fogAreaInfoBean.getControllers_zt());
        fogControllerAdapter.notifyDataSetChanged();
        fogControllerAdapter.setOnItemClickListener(new FogControllerAdapter.onItemClickListener() {
            @Override
            public void onClickListener(int position) {
                if (CommonUtils.isFastDoubleClick()) {
                    return;
                }
                FogControllerItem fogControllerItem = datas.get(position);
                FogLampStateActivity.startAction(mContext, fogControllerItem);
            }
        });

        refreshTime.setRightText(fogAreaInfoBean.getGxsj());//更新时间
        workModel = String.valueOf(fogAreaInfoBean.getGzms());//工作模式
        lightModel = fogAreaInfoBean.getWdkz() + "";//雾灯控制编码

        if (fogAreaInfoBean.getGzms() == 2 || fogAreaInfoBean.getGzms() == 5) {
            setEnable(tvSdgy, false);
            setEnable(tvQxgy, true);
        } else {
            setEnable(tvSdgy, true);
            setEnable(tvQxgy, false);
        }
        timeSwitch.setChecked(fogAreaInfoBean.isSfds());

        timeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isAuto)
                    mPresenter.http_updateFogAreaTimer(mActivity, UserInfoUtils.getInstance().getToken(mContext), fogAreaInfoBean.getWqbm(), isChecked);

                isAuto = false;
            }
        });

        if ("手动".equals(fogAreaInfoBean.getGzmssm())) {

            countSecond = fogAreaInfoBean.getSdsc() * 60 - (int) TimeUtils.timeToMills(fogAreaInfoBean.getSdsjsm());

            if (countSecond > 0) {
                tvCountdown.setRightText(TimeUtils.secondToMin(countSecond));
                mHadler.sendEmptyMessageDelayed(1, 1000);
            } else {
                tvCountdown.setRightText("正在切换");
            }
        } else {
            tvCountdown.setRightText("--");
        }


    }


    private Handler mHadler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (pageType == 3) {
                countSecond--;
                if (countSecond > 0) {
                    tvCountdown.setRightText(TimeUtils.secondToMin(countSecond));
                    mHadler.sendEmptyMessageDelayed(1, 1000);
                } else {
                    tvCountdown.setRightText("正在切换");
                }
            }
        }
    };


    public void fogAreaInfo(FogAreaInfoBean fogAreaInfoBean) {
        isError = false;
        if (fogAreaInfoBean == null) return;
//        tv_eqiup_name.setText(fogAreaInfoBean.getWqmc());//雾区名称
        tvNjdLevel.setRightText(fogAreaInfoBean.getNjddj());//能见度等级
        tvNjd.setRightText(String.format("%dm", fogAreaInfoBean.getNjd()));//能见度
        tvOneMinuteNjd.setRightText(String.format("%dm", fogAreaInfoBean.getNjdyfz()));//一分钟能见度
        tvTenMinuteNjd.setRightText(String.format("%dm", fogAreaInfoBean.getNjdsfz()));//十分钟能见度
        tvWeather.setRightText(fogAreaInfoBean.getWqtq());//天气
        tl_work_mode.setRightText(fogAreaInfoBean.getGzmssm());//工作模式
        tl_foglight_controller.setRightText(fogAreaInfoBean.getWdkzsm());//雾灯控制
        refreshTime.setRightText(fogAreaInfoBean.getGxsjgs());//更新时间
        workModel = fogAreaInfoBean.getGzms();//工作模式
        lightModel = fogAreaInfoBean.getWdkzbm();//雾灯控制编码
    }


    /**
     * 雾灯控制
     */
    @Override
    public void foglightInfo(FoglightDetailInfo bean) {
        isError = false;
        if (bean == null) return;
//        tv_eqiup_name.setText(bean.getWdmc());//雾灯名称
        item_equipmentnumber.setRightText(bean.getWdbm() + "");
//        item_control.setRightText(String.valueOf(bean.getKzqbm()));
        item_control.setRightText(String.valueOf(bean.getKzqmc()));
        item_voltage.setRightText(String.valueOf(bean.getXdcdysm()) + "V");//蓄电池电压
        item_deviceStatus.setRightText(bean.getSbztsm());//设备状态
        item_lampTemp.setRightText(String.valueOf(bean.getWdwd()) + "℃");//雾灯温度
        tl_solar_energy.setRightText(bean.getTyndysm() + "V");//太阳能电压
        itemDoorStatus.setRightText(bean.getMztsm());//门状态
        itemTemperature.setRightText(bean.getWdztsm());//温度状态
        itemVoltageStatus.setRightText(bean.getDyztsm());//电压状态
        itemLEDStatus.setRightText(bean.getLedztsm());//LED状态
        itemRadarStatus.setRightText(bean.getLdztsm());//雷达状态
        itemDevicePairing.setRightText(bean.getSbpdsm());//设备配对
        itemRefreshTime.setRightText(bean.getGxsjgs());//更新时间
    }


    /**
     * 能见度检测仪
     */
    @Override
    public void visibilityDetectInfo(VisibilityControllerDetailBean bean) {
//        isError = false;
//        if (bean == null) return;
//        itemsEquipCode.setRightText(bean.getSbbm());//设备编码=====控制器编码？？？
//        tl_device_name.setRightText(bean.getSbmc());//检测仪名称
//        itemsBelongFogZone.setRightText(bean.getWqmc());//雾区名称
//        tl_comm_params.setRightText(bean.getTxcs());//通讯参数
//        tl_work_mode.setRightText(bean.getGzmssm());//工作模式
//        tl_alarm_line.setRightText(String.valueOf(bean.getBjfzxx()) + "m" + "~" + String.valueOf(bean.getBjfzsx()) + "m");
//        tl_alarm_offline.setRightText(String.valueOf(bean.getBjfzxx()) + "m");//报警阀值下线
//        tl_alarm_online.setRightText(String.valueOf(bean.getBjfzsx()) + "m");//报警阀值上线
//        itemsEquipStqtus.setRightText(bean.getSbztsm());//设备状态
//        itemsRefreshTime.setRightText(bean.getGxsjgs());//更新时间
//        workModel = bean.getGzms();
    }

    @Override
    public void updateFogAreaTimerInfo(CommonEntity entity) {
        if (entity.getCzjg() == 0) {
            ToastUtil.showShort(mContext, "操作成功");
        } else
            ToastUtil.showShort(mContext, "操作失败");
    }


    @Override
    public void updtaeFogLightMode(ArrayList<UpdateWorkModeResultBean.Item2Bean> resultBean) {

        if (null != resultBean) {
            if (resultBean != null) {
                setEnable(tvSdgy, true);
                setEnable(tvQxgy, false);
                ToastUtil.showShort(mContext, "取消干预成功");
            } else {
                ToastUtil.showShort(mContext, "取消干预失败");
            }
        }

    }

    public void visibilityDetectInfo(EquipListItemBean bean) {
        isError = false;
        if (bean == null) return;
        itemsEquipCode.setRightText(bean.getJcybm());//设备编码=====控制器编码？？？
        tl_device_name.setRightText(bean.getName());//检测仪名称
        itemsBelongFogZone.setRightText(bean.getWqmc());//雾区名称
        tl_comm_params.setRightText(bean.getTxcs());//通讯参数
        tl_work_mode.setRightText(bean.getGzmssm());//工作模式
        tl_alarm_line.setRightText(String.valueOf(bean.getBjfzxx()) + "m" + "~" + String.valueOf(bean.getBjfzsx()) + "m");
        tl_alarm_offline.setRightText(String.valueOf(bean.getBjfzxx()) + "m");//报警阀值下线
        tl_alarm_online.setRightText(String.valueOf(bean.getBjfzsx()) + "m");//报警阀值上线
        itemsEquipStqtus.setRightText(bean.getSbztsm());//设备状态
        itemsRefreshTime.setRightText(bean.getGxsj());//更新时间
        workModel = bean.getGzms();
    }


//    private void setPushVisisblityInfo(String jsonMessage) {
//        if (TextUtils.isEmpty(jsonMessage)) return;
//
//        Gson gson = new Gson();
//        VisibilityControllerDetailBean detailBean = gson.fromJson(jsonMessage, VisibilityControllerDetailBean.class);
//        if(!TextUtils.equals(typeCode, detailBean.getJcybm()))return;
//        tl_work_mode.setRightText(detailBean.getGzmssm());//工作模式
//        tl_alarm_line.setRightText(String.valueOf(detailBean.getBjfzxx()) + "m" + "~" + String.valueOf(detailBean.getBjfzsx()) + "m");
//        tl_alarm_offline.setRightText(String.valueOf(detailBean.getBjfzxx()) + "m");//报警阀值下线
//        tl_alarm_online.setRightText(String.valueOf(detailBean.getBjfzsx()) + "m");//报警阀值上线
//        itemsEquipStqtus.setRightText(detailBean.getSbztsm());//设备状态
//    }

    boolean isAuto = false;

    private void setPushVisisblityInfo(String jsonMessage) {
        if (TextUtils.isEmpty(jsonMessage)) return;

        Gson gson = new Gson();
        FogZoneListItemBean detailBean = gson.fromJson(jsonMessage, FogZoneListItemBean.class);
        if (!TextUtils.equals(fogZone.getWqbm(), detailBean.getWqbm())) return;
        fogZone = detailBean;
        tvKzcl.setRightText(detailBean.getKzclsm());
        if (!detailBean.getNjddj().equals("-1"))
            tvNjdLevel.setRightText(detailBean.getNjddj());//能见度等级
        else
            tvNjdLevel.setRightText("-");
        tvNjd.setRightText(String.format("%dm", detailBean.getNjd()));//能见度
        if ( detailBean.getNjdyfz()>ConstantsField.MAXNJD)
            tvOneMinuteNjd.setRightText(String.format("%dm", detailBean.getNjdyfz()));//一分钟能见度
        else
            tvOneMinuteNjd.setRightText("-");
        if ( detailBean.getNjdsfz()>ConstantsField.MAXNJD) {
            tvTenMinuteNjd.setRightText(String.format("%dm", detailBean.getNjdsfz()));//十分钟能见度
//            tvWeather.setRightText("晴朗");
        } else {
            tvTenMinuteNjd.setRightText("-");
//            tvWeather.setRightText("-");

            //tvWeather.setRightText(detailBean.getLmzt());//天气
        }
//        tvWeather.setRightText(detailBean.getLmzt());
        tvWeather.setRightText(detailBean.getTqdmsm());
        tl_work_mode.setRightText(detailBean.getGzmssm());//工作模式
        // sp_work_mode.setSelection(detailBean.getGzms() - 1);
//        tl_foglight_controller.setRightText(detailBean.getWdkzsm());//雾灯控制
        datas.clear();
        datas.addAll(detailBean.getControllers_zt());
       fogControllerAdapter.notifyDataSetChanged();


        refreshTime.setRightText(detailBean.getGxsj());//更新时间
        workModel = String.valueOf(detailBean.getGzms());//工作模式
        lightModel = detailBean.getWdkz() + "";//雾灯控制编码
        if (timeSwitch.isChecked() != detailBean.isSfds()) {
            isAuto = true;
            timeSwitch.setChecked(detailBean.isSfds());
        }


        if (mHadler.hasMessages(1)) {
            mHadler.removeMessages(1);
        }


        if (detailBean.getGzms() == 2 || detailBean.getGzms() == 5) {
            setEnable(tvSdgy, false);
            setEnable(tvQxgy, true);
        } else {
            setEnable(tvSdgy, true);
            setEnable(tvQxgy, false);
        }
//        if("手动".equals(fogZone.getGzmssm())) {
//            countSecond=fogZone.getSdsc()*60- (int) TimeUtils.timeToMills(fogZone.getSdsjsm());
//            if(countSecond>0){
//                tvCountdown.setRightText(TimeUtils.secondToMin(countSecond));
//                mHadler.sendEmptyMessageDelayed(1,1000);
//            }else{
//                tvCountdown.setRightText("正在切换");
//            }
//        }else{
//            tvCountdown.setRightText("--");
//        }


    }


    private void setEnable(TextView tv, boolean enable) {
        if (enable) {
            tv.setEnabled(enable);
            tv.setBackgroundResource(R.drawable.shape_round_cerners_bg);
        } else {
            tv.setEnabled(enable);
            tv.setBackgroundResource(R.drawable.shape_round_cerners_bg_enable);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if(requestCode==100&&resultCode==100&&data!=null){
//            UpdateWorkModeResultBean.Item1Bean bean= (UpdateWorkModeResultBean.Item1Bean) data.getSerializableExtra(ConstantsField.ITEM);
//            tl_foglight_controller.setRightText(bean.getWdkzsm());//雾灯控制
//            lightModel = bean.getWdkz()+"";//雾灯控制编码
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHadler.hasMessages(1)) {
            mHadler.removeMessages(1);
        }

        RxBus.getInstance().unRegister(UPDATE_JCY);
    }
}
